package su.myspringbootprojects.springsecuritylearn.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import su.myspringbootprojects.springsecuritylearn.entity.ApplicationUser;
import su.myspringbootprojects.springsecuritylearn.repository.UserRepository;

import java.util.Collections;

/**
 * Класс DatabaseUserDetailsService
 * <p/>
 * Сервис для использования БД в качестве источника данных о пользователях для корректной аутентификации и авторизации
 * <p/>
 *
 * @author petr.mikhailin
 * created 04.07.2024 9:04
 */
@Service
public class DatabaseUserDetailsService implements UserDetailsService {
    private final UserRepository userRepository;

    @Autowired
    public DatabaseUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ApplicationUser user = userRepository.findByEmail(username); //fetch user from db
        if(user == null){
            throw  new UsernameNotFoundException("User Not found");
        }
        //Retrieve user roles
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+user.getRole().getRoleName());
        //create User object
        return new User(user.getEmail(),user.getPassword(), Collections.singleton(authority));
    }
}
